package cc.messcat.dao.fupin;

import cc.messcat.common.dao.BaseDaoImpl;
import cc.messcat.dao.system.UserDao;
import cc.messcat.entity.fupin.VisitRecd;
import cc.messcat.entity.system.McUser;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Repository("visitRecdDao")
public class VisitRecdDaoImpl extends BaseDaoImpl<VisitRecd>  implements VisitRecdDao {

	@Autowired
	UserDao userDao;
	
	@Autowired
	PoorFamilyDao poorFamilyDao;
	
	@Override
	@SuppressWarnings("all")
	public List<VisitRecd> getRetrieveByPID(McUser user, Long id) throws Exception {
		
		List<Map> list = getCurrentSession().createSQLQuery("select id as id, PID as pid,target as target,content as content,remarks as remarks,"
			+ " ACCESSORY_Url as ACCESSORY_Url,ACCTOTAL as acctotal, EDITTOR as editto,"
			+ " ADDTOR as addtor ,ADD_TIME as add_time , UP_TIME as up_time from visit_recd as vr where  is_del = '0' and vr.pid="+id)
			.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
		List<VisitRecd> result = new ArrayList<>();
		for (Map e : list) {
			VisitRecd temp = new VisitRecd();
			temp.setId(Long.parseLong(e.get("id").toString()));
			temp.setAccTotal(e.get("acctotal") == null ? "" : e.get("acctotal").toString());
			temp.setAccessoryUrl(e.get("ACCESSORY_Url") == null ? "" : e.get("ACCESSORY_Url").toString());
			temp.setAddTime(e.get("add_time") == null ? null : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(e.get("add_time").toString()));
			temp.setContent(e.get("content") == null ? "" :  e.get("content").toString());
			temp.setIsDel("0");
			temp.setRemarks(e.get("remarks") == null ? "" :e.get("remarks").toString());
			temp.setTarget(e.get("target") == null ? "" : e.get("target").toString());
			temp.setUpTime(e.get("up_time") == null ? null : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(e.get("up_time").toString()));
			temp.setAddtor(userDao.get(Long.parseLong(e.get("addtor").toString())));
			temp.setEdittor(user);
			temp.setPoorFamily(poorFamilyDao.get(Long.parseLong(e.get("pid").toString())));
			
			result.add(temp);
		}
		return result;
	}

	@Override
	public Long addVisitRecd(VisitRecd visitRecd) {
		return (Long) getCurrentSession().save(visitRecd);
	}

	@Override
	public Long getCountByPid(Long id) {
		Object result = getCurrentSession().createQuery("select count(*) from VisitRecd where isDel=0 and pid="+id).uniqueResult();
		return Long.valueOf(result.toString());
	}

}
